<template>
  <div class="conter">
    <el-form :inline="true" :model="datas.searchParam" class="demo-form-inline">
      <el-form-item label="计划时间">
        <el-date-picker v-model="start_time" value-format="yyyy-MM-dd" style="width: 260px" type="daterange" align="right" unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="getPageInfos" />
      </el-form-item>
      <el-form-item label="计划名称或ID">
        <el-input v-model="datas.searchParam.name" @change="getcnahe" placeholder="计划名称或ID"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getPageInfos">查询</el-button>
        <!-- <el-button type="primary" @click="upclearud">123456</el-button> -->
      </el-form-item>
    </el-form>
    <el-table :data="tableData" v-loading="loading" border style="width: 100%">
      <el-table-column prop="unitName" label="组名称" width="180">
      </el-table-column>
      <el-table-column prop="campaignName" label="对应计划名称">
      </el-table-column>
      <el-table-column prop="bidDetail" label="成本上限">
      </el-table-column>
      <el-table-column prop="bidDetail" label="操作">
        <template slot-scope="scope">
          <el-button @click="copyconter(scope.row)" type="text">复制</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="total" class="right-pagination">
      <el-pagination :current-page="datas.pageInfo.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="datas.pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getPageInfossize" @current-change="getPageInfoscurr" />
    </div>
    <el-drawer title="批量创建配置" :visible.sync="copyItems" direction="rtl" size="40%" :modal-append-to-body="false" :close-on-press-escape="false" :before-close="copyHeidengs">
      <el-form ref="form" :model="jhConfig" label-width="80px">
        <el-form-item label="计划">
          <el-select v-model="jhConfig.campaignId" placeholder="计划">
            <el-option v-for="item in campaignIds" :key="item.campaignId" :label="item.campaignName" :value="item.campaignId">
            </el-option>
          </el-select>
        </el-form-item>
        <h1 class="hters" v-if="0"> 转化途径</h1>
        <el-form-item label="转化途径" v-if="0">
          <el-radio-group v-model="jhConfig.merchantItemPutType">
            <el-radio-button :label="0">商品详情页</el-radio-button>
            <el-radio-button :label="72" disabled>快手个人主页</el-radio-button>
            <el-radio-button :label="192" disabled>直播预约</el-radio-button>
          </el-radio-group>
          <br />
          <div class="userinfobox" v-if="userinfolist">
            <div class="inmge">
              <img :src="userinfolist[0].visitorHeadUrl" alt="" class="userinage">
            </div>
            <div class="usernagid">
              <div class="names">
                {{userinfolist[0].visitorName}}
              </div>
              <div class="idhss">
                快手ID: {{userinfolist[0].visitorId}}
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="商品类型" v-if="0">
          <el-radio-group v-model="jhConfig.supportType">
            <el-radio-button :label="0">小店自营商品</el-radio-button>
            <el-radio-button :label="1" disabled>小店好物联盟商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品" v-if="0">
          <div class="noleters" v-if="!goods" @click="selectGoods">
            <i class="el-icon-circle-plus-outline"></i> 选择商品
          </div>
          <div class="getusher" v-else @click="selectGoods">
            <div class="leftringm">
              <img :src="goods.imageUrl[0]" alt="" class="cnnghds">
            </div>
            <div class="rightsb">
              <div class="titlre">
                {{goods.title}}
              </div>
              <div class="cinrifd">
                ID:{{goods.itemId}}
              </div>
              <div class="proiuey">
                价格： ￥{{getfinherr(goods.maxPrice)}}
              </div>
            </div>
          </div>
        </el-form-item>
        <h1 class="hters" v-if="0"> 目标设置</h1>
        <el-form-item label="转化目标" v-if="0">
          <el-radio-group v-model="jhConfig.ocpxActionType">
            <el-radio-button :label="395">商品购买</el-radio-button>
            <el-radio-button :label="192">ROI</el-radio-button>
            <el-radio-button :label="72">粉丝关注</el-radio-button>
            <el-radio-button :label="917">涨粉ROI</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <h1 class="hters" v-if="0"> 定向设置</h1>
        <el-form-item label="定向选择" v-if="0">
          <el-radio-group v-model="jhConfig.targetSettingType">
            <el-radio-button :label="1">智能优选</el-radio-button>
            <el-radio-button :label="2" disabled>自定义</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <div class="unse" v-if="jhConfig.targetSettingType === 1 && 0">
          <el-form-item label="地区">
            <el-radio-group v-model="jhConfig.adDspTarget.regionType">
              <el-radio-button :label="0">不限</el-radio-button>
              <el-radio-button :label="1">按省份</el-radio-button>
              <el-radio-button :label="2">按级别</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="jhConfig.adDspTarget.regionType === 1">
            <el-cascader :options="shengshi" v-model="jhConfig.adDspTarget.regionCategoryIds" :show-all-levels="false" :props="props" collapse-tags clearable @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item v-if="jhConfig.adDspTarget.regionType === 2">
            <el-cascader :options="jibei" v-model="jhConfig.jibei" :show-all-levels="false" :props="props" collapse-tags clearable @change="handleChange"></el-cascader>
          </el-form-item>
        </div>
        <el-form-item label="年龄" v-if="0">
          <el-checkbox-group v-model="jhConfig.adDspTarget.age" @change="changeFuns">
            <el-checkbox-button v-for="type in ages" :key="type.label" :label="type.label">{{ type.name }}</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="性别" v-if="0">
          <el-radio-group v-model="jhConfig.adDspTarget.gender">
            <el-radio-button label="">不限</el-radio-button>
            <el-radio-button label="M">男</el-radio-button>
            <el-radio-button label="W">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排除人群" v-if="0">
          <el-radio-group v-model="jhConfig.pepoles">
            <el-radio-button :label="0">不限</el-radio-button>
            <el-radio-button :label="1" disabled>排除人群</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <h1 class="hters"> 投放设置</h1>
        <el-form-item label="日预算" v-if="0">
          <el-input placeholder="请输入日预算" :min="300" :max="2000000" v-model="jhConfig.dayBudget" style="width: 200px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="投放方式" v-if="0">
          <el-radio-group v-model="jhConfig.cpaBid_type">
            <el-radio-button :label="0">成本保护</el-radio-button>
            <el-radio-button :label="1">最大转化</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="nameTuers +'上限'" v-if="jhConfig.ocpxActionType === 395 || jhConfig.ocpxActionType === 192">
          <el-row justify="center">
            <el-col :span="6">
              <el-input-number :placeholder="'最低'+nameTuers" :step="0.1" v-model="big.min">
              </el-input-number>
            </el-col>
            <el-col :span="1">
              -
            </el-col>
            <el-col :span="6">
              <el-input-number :placeholder="'最高'+nameTuers" :step="0.1" :min="big.min" v-model="big.max">
              </el-input-number>
            </el-col>
            <el-col :span="2">
              跨度
            </el-col>
            <el-col :span="6">
              <el-input-number placeholder="跨度" :step="0.1" :max="big.max" v-model="big.stip">
              </el-input-number>
            </el-col>
            <el-col :span="3">
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="重复" v-if="jhConfig.ocpxActionType === 395 || jhConfig.ocpxActionType === 192">
          <el-input-number placeholder="重复" :step="1" :min="1" v-model="big.confs">
          </el-input-number>
        </el-form-item>
        <el-form-item label="投放时间" v-if="0">
          <el-radio-group v-model="jhConfig.outtimes">
            <el-radio-button :label="0">从今天开始长期投放</el-radio-button>
            <el-radio-button :label="1" disabled>设置开始和结束日期</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="投放时段" v-if="0">
          <el-radio-group v-model="jhConfig.daytimes">
            <el-radio-button :label="0">全天</el-radio-button>
            <el-radio-button :label="1" disabled>特定时间</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <h1 class="hters"> 创意组成方式</h1>
        <el-form-item label="创意组成方式">
          <el-radio-group v-model="jhConfig.creativeBuildType">
            <el-radio-button :label="0">自主选择</el-radio-button>
            <el-radio-button :label="2">系统优选</el-radio-button>
            <el-radio-button :label="1">自主选择+系统优选</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告组名称" v-if="0">
          自动生成
        </el-form-item>
        <el-form-item label="投放管家" v-if="0">
          <el-radio-group v-model="jhConfig.guanjia">
            <el-radio-button :label="0">不使用</el-radio-button>
            <el-radio-button :label="1" disabled>系统模板</el-radio-button>
            <el-radio-button :label="2" disabled>自定义模板</el-radio-button>
            <el-radio-button :label="3" disabled>智能调控</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <h1 class="hters" v-if="0"> 优化设置</h1>
        <el-form-item label="一键继承" v-if="0">
          <el-radio-group v-model="jhConfig.jichengs">
            <el-radio-button :label="0">开启</el-radio-button>
            <el-radio-button :label="1">关闭</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预计">
          {{get_nuberis}}条计划 ; 需要 {{unshrrs}} 条视频
        </el-form-item>
        <h1 class="hters" v-if="jhConfig.creativeBuildType !== 2"> 选择素材</h1>
        <el-form-item label="选择素材" v-if="jhConfig.creativeBuildType !== 2">
          <el-col :span="10">
            <div class="litser">
              <div class="lister" :class="{activet: item._id === activetNa}" @click="activetNaFun(item._id)" v-for="item in dir_lists" :key="item._id">
                {{item.dirName}}
              </div>
            </div>
          </el-col>
          <el-col :span="14">
            <div class="rightlisster">
              <h2>文件列表</h2>
              <div class="litser">
                <div class="lister" v-for="(item, index) in file_list" :class="{slectClass: item.selectStatus}" @click="selectOrClearItem(item)" :key="item._id">
                  {{++index}}:{{item.name}}
                </div>
              </div>
              <div class="dd">
                共{{file_list.length}}条, 以选择{{get_conters}}条视频
              </div>
            </div>
            <div class="selectconters">
              <el-checkbox v-model="selectAll" @change="selectAllFun" :disabled="!file_list.length">全选</el-checkbox>
            </div>
            <div class="selectconters">
              <el-row>
                <el-col :span="10">
                  <el-input-number placeholder="开始" :min="0" :step="1" v-model="sterp_uper.start">
                  </el-input-number>
                </el-col>
                <el-col :span="10">
                  <el-input-number placeholder="结束" :max="file_list.length" :step="1" v-model="sterp_uper.end">
                  </el-input-number>
                </el-col>
                <el-col :span="4">
                  <el-button type="primary" @click="seletcynegr">选择</el-button>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer title="商品选择" size="50%" :visible.sync="shopListConters" direction="ltr" :modal-append-to-body="false" :close-on-press-escape="false" :before-close="shopListContersFun">
      <div class="bouurt">
        <el-table ref="sehectGoode" :data="shopeDataList" :selectable="selectableFun" highlight-current-row @current-change="shopeDataChange" style="width: 100%">
          <!-- <el-table-column type="selection" width="20">
          </el-table-column> -->
          <el-table-column property="date" label="商品信息" width="250">
            <template slot-scope="scope">
              <div class="inyusr">
                <div class="leftringm">
                  <img :src="scope.row.imageUrl[0]" alt="" class="cnnghds">
                </div>
                <div class="rightsb">
                  <div class="titlre">
                    {{scope.row.title}}
                  </div>
                  <div class="cinrifd">
                    ID:{{scope.row.itemId}}
                  </div>
                  <div class="proiuey">
                    价格： ￥{{getfinherr(scope.row.maxPrice)}}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column property="categoryName" label="类目" width="50">
          </el-table-column>
          <el-table-column property="last30dSalesCnt" label="30天销量" width="100">
          </el-table-column>
          <el-table-column property="normGoodCommentRate" label="好评率(%)" width="100">
          </el-table-column>
          <el-table-column property="stock" label="库存" width="50">
          </el-table-column>
          <el-table-column property="createTime" label="创建时间">
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
    <el-drawer title="创建进度" :modal="false" size="100%" :show-close="false" :close-on-press-escape="false" :visible.sync="cretedeStatusDarwer" direction="ttb" :before-close="clearDarwer">
      <div class="interbox">
        <h1 class="ontinters">*正在创建，请勿退出或刷新页面</h1>
        <div class="tersj">
          已创建{{tersinter}}条,成功{{uplters.yes}}条，失败{{uplters.none}}条
        </div>
        <div class="interss">
          <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"></el-progress>
        </div>
      </div>
    </el-drawer>
  </div>

</template>
<script>
import { get_zidinyilist, creted_program_nos, get_z_list, get_jh_list, get_user_info, get_goods_list, get_region_list, created_ca, get_item_ters, get_phodetel, get_phon_info, creted_poconters } from '../../api/kuaishou'
import { get_get_file, get_dir_api } from '../../api/my_server'

export default {
  name: 'Appins',

  data () {
    return {
      activetNa: '',
      storageData: null,
      lenthenid: null,
      start_time: [],
      cretedeStatusDarwer: false,
      tableData: [],
      loading: true,
      copyItems: false,
      shopListConters: false,
      dir_lists: [],
      file_list: [],
      creatives_datas: null,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 89)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      total: 0,
      datas: {
        searchParam: {
          promotionType: 2,
          searchLevel: 2,
          startTime: '',
          endTime: '',
          status: { "unit": { "value": [] } },
          creativeListType: 1,
          campaignIds: [],
          unitIds: [],
          sceneOrientedTypes: [0]
        },
        pageInfo: {
          pageNum: 1,
          pageSize: 10
        }
      },
      goods: null,
      sterp_uper: {
        start: '',
        end: ''
      },
      jhConfig_uer: null,
      ahhske: null,
      jhConfig: {
        campaignId: '', // 广告计划ID
        merchantItemPutType: 0,
        liveUserId: '', // 用户ID
        supportType: 0,
        itemId: '',
        ocpxActionType: 395, // 转化途径
        targetSettingType: 1,
        dayBudget: '',
        cpaBid_type: 0,
        cpaBid: '',
        creativeBuildType: 0,


        jibei: [],
        name: '',
        adDspTarget: {
          regionType: 0,
          regionCategoryIds: [],
          age: [''],
          gender: ''
        }
      },
      big: {
        max: '',
        min: '',
        stip: '',
        confs: 1
      },
      updirdata: {
        accountId: '',
        dirName: ''
      },
      price_arr: [],
      srrpuer: [],
      campaignIds: [],
      userinfolist: null,
      shopeDataList: [],
      shopeDataPost: {
        "itemId": "",
        "title": "",
        "categoryId": 0,
        "productStatus": 0,
        "pageInfo": {
          "pageNum": 1,
          "pageSize": 100
        },
        "needProductLabelType": false
      },
      shengshi: [],
      jibei: [],
      props: { expandTrigger: 'hover', multiple: true, label: "name", value: "id", children: "children" },
      ages: [
        {
          name: '不限',
          label: ''
        }, {
          name: '18-23',
          label: { min: 18, max: 23 }
        }, {
          name: '24-30',
          label: { min: 24, max: 30 }
        }, {
          name: '31-40',
          label: { min: 31, max: 40 }
        }, {
          name: '41-49',
          label: { min: 41, max: 49 }
        }, {
          name: '50+',
          label: { min: 50 }
        }
      ],
      originUnitId: '',
      selectAll: false,
      unitType: null,
      oldcreativeType: null,
      pohonter: [],
      cytypes: 0,
      tersinter: 0,
      uplters: {
        yes: 0,
        none: 0,
      }
    }
  },
  computed: {
    nameTuers () {
      if (this.jhConfig.ocpxActionType === 395) {
        return '出价'
      }
      if (this.jhConfig.ocpxActionType === 192) {
        return 'ROI'
      }
    },
    setNumberiOCnter () {
      // 组需要的视频数量
      if (this.jhConfig.creativeBuildType === 0) {
        return 15
      }
      if (this.jhConfig.creativeBuildType === 1) {
        return 10
      }
      return 0
    },
    unshrrs () {
      if (this.cytypes === 0) {
        return this.get_nuberis * 5
      }
      return this.setNumberiOCnter * this.get_nuberis
    },
    get_conters () {
      let nums = 0
      this.file_list.forEach(res => {
        if (res.selectStatus) nums++
      })
      return nums
    },
    get_nuberis () {
      if (this.big.min && this.big.max && this.big.stip) {
        let startNum = this.big.min
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.price_arr = []
        do {

          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.price_arr.push(startNum * 1)
          startNum = ((startNum * 1) + (this.big.stip * 1)).toFixed(2) * 1
        }
        while (startNum <= this.big.max)

        if (this.price_arr[this.price_arr.length - 1] * 1 !== this.big.max * 1) {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.price_arr.push(this.big.max * 1)
        }
        console.log('this.price_arr', this.price_arr)
        return this.price_arr.length * this.big.confs
      }
      return 0
    },
    percentage () {
      return (this.tersinter / this.get_nuberis) * 100
    }
  },
  created () {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 89)
    const start_srt = `${start.getFullYear()}-${start.getMonth() + 1}-${start.getDate()}`
    const end_srt = `${end.getFullYear()}-${end.getMonth() + 1}-${end.getDate()}`
    this.start_time = [start_srt, end_srt]
    this.getPageInfos()
    this.getregefun()
  },
  methods: {
    upclearud () {
      this.cretedeStatusDarwer = true
    },
    clearDarwer () {
      console.log('上传进度')
    },
    // 获取视频详情
    getPhonInfoFun (photoId) {
      const data = {
        photoId
      }
      return new Promise((resole, reject) => {
        get_phon_info.bind(this)(data).then(res => {
          resole(res)
        })
      })

    },
    seletcynegr () {
      if (!this.sterp_uper.start || !this.sterp_uper.end) {
        return
      }
      this.file_list.forEach((res, index) => {
        res.selectStatus = false
        if (index >= this.sterp_uper.start - 1 && index <= this.sterp_uper.end - 1) {
          res.selectStatus = true
        }
      })

    },
    selectOrClearItem (item) {
      item.selectStatus = !item.selectStatus
      const noseletins = this.file_list.find(res => {
        return !res.selectStatus
      })
      if (noseletins) {
        this.selectAll = false
      }
    },
    selectAllFun (status) {
      console.log('selectAlls', status)
      if (!status) {
        this.file_list.forEach(res => {
          res.selectStatus = false
        })
        return
      }
      this.file_list.forEach(res => {
        res.selectStatus = true
      })
    },
    activetNaFun (item) {
      this.activetNa = item
      this.selectAll = false
      this.getFlieListFun()
    },
    getFlieListFun () {
      get_get_file.bind(this)({
        ac_id: this.updirdata.accountId,
        dir_id: this.activetNa
      }).then(res => {
        try {
          const jsonData = JSON.parse(res)
          if (jsonData.code === 200) {
            console.log('jsonData', jsonData)
            this.file_list = jsonData.data.map(eer => {
              eer.selectStatus = false
              return eer
            })
          } else {
            this.$message.error(jsonData.msg)
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }
      })
    },
    getDirList (accountId) {
      this.activetNa = ''
      this.updirdata.accountId = accountId
      get_dir_api.bind(this)(this.updirdata).then(res => {
        try {
          const jsonData = JSON.parse(res)
          if (jsonData.code === 200) {
            console.log('jsonData', jsonData)
            this.dir_lists = jsonData.data
          } else {
            this.$message.error(jsonData.msg)
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }
      })
    },
    getItemTers (unitId) {
      const updatas = {
        unitId
      }
      return new Promise((resole, reject) => {
        get_item_ters.bind(this)(updatas).then(res => {
          console.log('res', res)
          try {
            const jsondata = JSON.parse(res)
            if (jsondata.result === 1) {
              this.jhConfig = jsondata.data.unit
              this.jhConfig_uer = jsondata.data.unit
              resole()
            }
          } catch (error) {
            this.$message.error('获取失败', error)
          }
        })
      })

    },
    async onSubmit () {
      if (!this.big.max || !this.big.min || !this.big.stip) {
        this.$message.error('缺少必要参数')
        return
      }
      if (this.big.min > this.big.max) {
        this.$message.error('最小出价大于最大出价')
        return
      }
      if (this.unshrrs > this.get_conters) {
        this.$message.error('视频缺少' + (this.unshrrs - this.get_conters) + '个')
        return
      }
      this.setinTrperis()
      this.upclearud()
      return

    },
    setinTrperis () {
      this.srrpuer = []
      this.pohonter = []
      console.log('this.price_arr', this.price_arr)
      for (let i = 0; i < this.big.confs; i++) {
        this.price_arr.forEach(res => {
          this.srrpuer.push(res)
        })
      }
      this.file_list.forEach(res => {
        if (res.selectStatus) {
          this.pohonter.push(res.photo_id)
        }
      })
      this.jeruters()
    },
    async jeruters () {
      console.log('this.srrpuer', this.srrpuer)
      if (!this.srrpuer || !this.srrpuer.length) {
        this.$message.success('批量创建已完成，将在3秒后刷新页面')
        setTimeout(_ => {
          location = location
        }, 3000)
        return
      }
      const getMerbers = this.srrpuer.splice(0, 1)
      if (!getMerbers) return
      const unitId = await this.upacdatas(getMerbers[0])

      this.upLadFunters(unitId)
    },
    // 创建广告组
    upacdatas (nemru) {
      const updata = this.formaterData(nemru)
      return new Promise((resole, reject) => {
        created_ca.bind(this)(updata).then(res => {
          try {
            const jsondata = JSON.parse(res)
            if (jsondata.result === 1) {
              this.unitType = jsondata.data[0]
              this.ahhske = jsondata.data[0]
              resole(jsondata.data[0])

            }
          } catch (error) {
            this.$message.error('获取失败', error)
          }
        })
      })

    },
    formaterData (nemru) {
      const times = new Date()
      const updaterts = {
        "merchantItemPutType": '',
        "supportType": '',
        "itemId": '', // 商品ID
        "url": '',
        "reservationId": "", // *
        "liveUserId": '', // 用户ID
        "putType": 0, // *
        "targetSettingType": '', // 定向设置*
        "purchaseIntention": '', // *
        "celebrity": '', // *
        "templateId": '', // *
        "speed": '', // 不限设置5 投放方式 1 - 加速投放；2 - 平滑投放；3-优先低成本（投放时间范围只可为全天；预算不可为不限或空）5-nobid
        "ocpxActionType": '', // 转化目标 72：小店通商品和主页推广，转化目标“涨粉”；395：小店通商品和主页推广，转化目标“订单支付”，192：直播推广 ROI； 917粉丝ROI
        "dayBudget": '', // 预算
        "bid": '',
        "name": '',
        "schedule": "", // 投放时段
        "uri": '',
        "autoTarget": '', // *
        "bidType": '', // 优化目标出价类型 当前只支持 OCPM) 10
        "cpcType": '', // *
        "deepConversionBid": 0, // *
        "deepConversionType": 0, // *
        "unitType": 7, // 创意制作方式 4 自定义
        "unitSourceType": 1, // *
        "showMode": 2, //创意展现方式	1 - 轮播；2 - 优选
        "sceneId": [ // *
          6,
          7
        ],
        "resourceId": 1, // *
        "taobaoUrlType": 0, // *
        "creativeBuildType": 0, // 创意组成方式0自主选择 1 自主选择+系统优选 2 系统优选
        "targetExtend": 0, // *
        "extendsAccountId": 0, // *
        "extendsUnit": {
          "extendsUnitId": null, // 继承广告组ID
          "isExtends": false // extendsUnitId 不为空 为true
        },
        "modified": '', // *
        "extendsAccount": 0, // *
        "cpaBid": '', // 投放方式 最大化为0
        "beginTime": Date.parse(new Date()), // 开始时间
        "endTime": '', // 结束时间 没有为长期
        "scheduleTimeType": 0, // *
        "planLiveBeginTime": 0, // *
        "planLiveEndTime": 0, // *
        "splashAdSwitch": false, // *
        "simultaneousOptimizationSelected": false, // *
        "simultaneousOptimizationType": 0, // *
        "extendsUnitId": null, // 继承广告组ID
        "robot": { // *
          "unbind": true
        },
        "adDspTarget": {
          "age": '', //{min: "24", max: "30"}
          "gender": '', // 性别‘’不限 M 男 W 女
          "purchaseIntention": null, // *
          "celebrity": null, // *
          "excludePopulation": [], // *
          "corePopulationParam": { // *
            "categoriesIds": [], // *
            "categoriesNames": [], // *
            "label": [] // *
          },
          "regionCategoryNames": [], // 城市名称
          "regionCategoryIds": [], // 城市ID
          "regionType": 0, // 地区类型0不限1城市2级别
          "population": [], // *
          "paidAudience": [], // *
          "enginePopulation": [], // *
          "platform": {} // *
        },
        "campaignId": '', // 广告计划ID
        "originUnitId": ''
      }
      for (let key in updaterts.adDspTarget) {
        console.log('objk:', key, updaterts.adDspTarget[key])
        updaterts.adDspTarget[key] = this.jhConfig.target[key]
      }
      for (let key in updaterts) {
        if (key !== 'adDspTarget') updaterts[key] = this.jhConfig[key]
      }
      updaterts.url = updaterts.uri
      updaterts.originUnitId = this.originUnitId
      var a = (new Date()).toLocaleDateString()//获取当前日期
      a = a.replace(/\//g, '-');
      updaterts.beginTime = new Date(a).getTime()
      updaterts.name = 'GL-TFTP:' + times.getTime()
      if (this.jhConfig.ocpxActionType === 192) {
        updaterts.cpaBid = 0
        updaterts.roiRatio = nemru * 1
      } else if (this.jhConfig.ocpxActionType === 395) {
        updaterts.cpaBid = parseInt(nemru * 1000)
      }
      const updata = {
        "unitTypes": [updaterts]
      }
      return updata
    },
    changeFuns () {
      if (this.jhConfig.adDspTarget.age.length === 0) {
        this.jhConfig.adDspTarget.age = ['']
        return
      }
      if (this.jhConfig.adDspTarget.age[this.jhConfig.adDspTarget.age.length - 1] === '') {
        this.jhConfig.adDspTarget.age = ['']
        return
      }
      const noters = this.jhConfig.adDspTarget.age.indexOf('')
      if (noters !== -1) {
        this.jhConfig.adDspTarget.age.splice(noters, 1)
      }
    },
    handleChange (row) {
      console.log('row', row)
    },
    segerter (arr) {
      arr.forEach(item => {
        if (item.children && !item.children.length) {
          delete item.children
          return
        }
        if (item.children && item.children.length) {
          this.segerter(item.children)
        }
      });
    },
    getregefun () {
      // 获取省市
      get_region_list.bind(this)({ categoryType: 2 }).then(res => {
        try {
          const jsondata = JSON.parse(res)
          if (jsondata.result === 1) {
            this.shengshi = jsondata.data
            this.segerter(this.shengshi)
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }
      })
      // 级别
      get_region_list.bind(this)({ categoryType: 3 }).then(res => {
        try {
          const jsondata = JSON.parse(res)
          if (jsondata.result === 1) {
            this.jibei = jsondata.data
            this.segerter(this.jibei)
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }
      })
    },
    shopeDataChange (row) {
      this.goods = row
      this.jhConfig.itemId = row.itemId
    },
    selectableFun (row) {
      console.log('roww', row)
    },
    copyHeidengs () {
      this.copyItems = false
    },
    getfinherr (row) {
      return (row / 100).toFixed(2) * 1
    },
    selectGoods () {
      this.shopListConters = true
      get_goods_list.bind(this)(this.shopeDataPost).then(res => {
        try {
          const jsondata = JSON.parse(res)
          console.log('jsondata', jsondata)
          if (jsondata.result === 1) {
            this.shopeDataList = jsondata.data.data.filter(ew => {
              return ew.productStatus === 1
            })
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }
      })
    },
    shopListContersFun () {
      this.shopListConters = false
    },
    uuid () {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      return uuid;
    },
    // 发布素材
    upLadFunters (unitId) {
      const times = new Date()
      let creativeType = null
      if (this.cytypes === 1) {
        const conyer = {
          "campaignId": 859090829,
          "unitId": 1622091395,
          "displayInfo": {
            "actionBar": "立即购买",
            "description": "高档冰丝布男鞋，内外冰丝布，一双穿四季，舒适透气！"
          },
          "createTime": 1655456480501,
          "creativeMaterialType": 1,
          "creativeType": 14,
          "appDetailType": 0,
          "newExposeTag": [
            {
              "text": "爆款秒杀",
              "url": ""
            },
            {
              "text": "人气推荐",
              "url": ""
            }
          ],
          "photoId": "5230368093741953466",
          "coverUrl": "https://p4.a.yximgs.com/upic/2022/06/06/22/BMjAyMjA2MDYyMjIxMDZfMjc1MzEyMzUxNV83NjIwNTc4MDM1N18wXzM=_B38c1a13468c6a361fb458ead3dc0e6d0.jpg?tag=1-1654525348-unknown-0-okfikdb0us-5b44310010dfb583&clientCacheKey=3xdew48rukjmghk.jpg&di=6541713f&bp=10000",
          "coverWidth": 720,
          "coverHeight": 1280,
          "uuid": "24041388441",
          "id": 0,
          "liveTheme": "",
          "name": "拷贝 自定义创意_20220606_22:20asf:31_8",
          "recommendation": "高档冰丝布男鞋",
          "extraCoverData": "{\"composeType\":0}",
          "splashPictures": [],
          "splashPhotos": [],
          "reviewStatus": 2,
          "liveCreativeType": 0,
          "createSourceType": 1,
          "actionbarClickUrl": "",
          "clickUrl": "",
          "adPhotoPlayedT3sUrl": "",
          "impressionUrl": "",
          "advCardOption": 0,
          "advCardList": [],
          "siteId": 0,
          "downloadPageType": 0,
          "downloadPageUrl": "",
          "creativeCategory": "",
          "creativeTag": "",
          "auditError": {
            "auditErrorStickerTitle": [],
            "auditErrorDescriptionTitle": [],
            "auditErrorPhoto": [],
            "auditErrorCover": []
          },
          "materialAuditStatus": 0,
          "creativeStyleType": 0,
          "merchantLibraryId": null,
          "merchantProductId": "",
          "screenshots": "",
          "itemMaterial1": null
        }
        const upfile = []
        const leuryhter = this.pohonter.splice(0, this.creatives_datas.length)
        const terspeir = leuryhter.map(tiye => {
          const data = {
            photoId: tiye
          }
          return get_phon_info.bind(this)(data)
        })
        Promise.all(terspeir).then(eerre => {
          console.log('eerre', eerre)
          this.creatives_datas.forEach((res, index) => {
            let sjhger = JSON.parse(JSON.stringify(conyer))
            for (let key in sjhger) {
              sjhger[key] = res[key] || sjhger[key]
            }
            sjhger.createTime = times.getTime()

            sjhger.name = 'ZDY' + this.uuid()
            sjhger.uuid = crypto.randomUUID();
            sjhger.id = 0
            sjhger.unitId = unitId.unitId
            sjhger.photoId = leuryhter[index]
            console.log('leuryhter[index]', leuryhter[index])
            upfile.push(sjhger)
          })
          eerre.forEach((ressr, index) => {
            try {
              const jsonData = JSON.parse(ressr)
              if (jsonData.result === 1) {
                upfile[index].coverHeight = jsonData.photoInfo.height
                upfile[index].coverWidth = jsonData.photoInfo.width
                upfile[index].coverUrl = jsonData.photoInfo.webpCoverUrls[0].url
              }
            } catch (error) {

            }
          })
          console.log('upfile', upfile)

          this.cretedNew(upfile)
        })
        return

      }
      if (this.cytypes === 0) {
        creativeType = {
          "actionBar": "",
          "packageName": "程序化创意_2022/06/16_00:13:0933",
          "stickerStyles": [],
          "coverSlogans": [],
          "verticalPhotoIds": [],
          "horizontalPhotoIds": [],
          "covers": [],
          "smartCover": '',
          "captions": [],
          "id": '',
          "unitId": '',
          "unitType": '',
          "actionbarClickUrl": "",
          "campaignId": '',
          "clickUrl": "",
          "createSourceType": '',
          "siteId": '',
          "downloadPageType": '',
          "downloadPageUrl": "",
          "creativeCategory": "",
          "creativeTag": "",
          "assetMining": '',
          "autoCreatePhoto": '',
          "advCardOption": '',
          "advCardList": []
        }
        for (let key in creativeType) {
          creativeType[key] = this.oldcreativeType[key]
        }
        // creativeType.covers = []
        creativeType.siteId = creativeType.siteId * 1
        // 视频id列表
        creativeType.packageName = 'POHT' + times.getTime()
        creativeType.unitId = unitId.unitId
        creativeType.id = 0
        creativeType.creativeCategory = ''
        // creativeType.sceneId = [6, 7, 10]
        console.log('creativeType222', creativeType)

        // console.log('this.file_list', this.file_list)
        creativeType.verticalPhotoIds = this.pohonter.splice(0, 5)
        // console.log('creativeType.verticalPhotoIds', creativeType.verticalPhotoIds)
        this.cretedNew(creativeType)
        return
      }


    },
    // 创建素材
    cretedNew (data) {
      this.ahhske.sceneId = this.jhConfig_uer.sceneId
      this.ahhske.adDspTarget.behaviorInterest = this.ahhske.adDspTarget.behaviorInterest || ''
      this.ahhske.adDspTarget.platform = this.ahhske.adDspTarget.platform || {}
      this.ahhske.adDspTarget.regionCategoryIds = this.ahhske.adDspTarget.behaviorInterest || []
      this.ahhske.adDspTarget.regionCategoryNames = this.ahhske.adDspTarget.behaviorInterest || []
      this.ahhske.adDspTarget.schoolState = this.ahhske.adDspTarget.schoolState || []
      this.ahhske.adDspTarget.id = this.ahhske.adDspTarget.id || 0


      const url = `https://niu.e.kuaishou.com/create?mode=copy&promotionType=2&campaignId=${this.jhConfig.campaignId}&unitId=${this.unitType.unitId}&__accountId__=${this.updirdata.accountId}&originUnitId=${this.originUnitId}`
      if (this.cytypes === 0) {
        const datas = {
          creativeType: data,
          unitType: this.ahhske
        }
        creted_poconters.bind(this)(datas, url).then(res => {
          console.log('创建成功')
          this.tersinter++
          this.uplters.yes++
          this.jeruters()
        }).catch(err => {
          this.tersinter++
          this.uplters.none++
          this.jeruters()
        })
        return
      }
      if (this.cytypes === 1) {
        const datas = {
          creativeTypes: data,
          unitType: this.ahhske
        }
        creted_program_nos.bind(this)(datas, url).then(res => {
          console.log('创建成功222')
          this.tersinter++
          this.uplters.yes++
          this.jeruters()
        }).catch(err => {
          this.tersinter++
          this.uplters.none++
          this.jeruters()
        })
      }

    },
    getPhodetelFun (unitId) {
      const data = {
        unitId: unitId
      }
      return new Promise((resole, reject) => {
        get_phodetel.bind(this)(data).then(res => {
          try {
            const jsondata = JSON.parse(res)
            if (jsondata.result === 1) {
              if (!jsondata.advancedProgramCreativeType) {
                this.getPhodetelFunUnyer(unitId).then(res => {
                  this.cytypes = 1
                  resole()
                }).catch(err => {
                  reject()
                })
                return
              }
              this.cytypes = 0
              this.oldcreativeType = jsondata.advancedProgramCreativeType
              resole()
            }
          } catch (error) {
            this.$message.error('获取失败', error)
          }
        })
      })

    },
    getPhodetelFunUnyer (unitId) {
      const data = {
        unitId: unitId
      }
      return new Promise((resole, reject) => {
        get_zidinyilist.bind(this)(data).then(res => {
          try {
            const jsondata = JSON.parse(res)

            if (jsondata.result === 1) {
              if (jsondata.creatives && jsondata.creatives.creativeListParam && jsondata.creatives.creativeListParam.length) {
                this.creatives_datas = jsondata.creatives && jsondata.creatives.creativeListParam
                if (this.creatives_datas && this.creatives_datas.length) {
                  this.creatives_datas.forEach(eer => {
                    for (let f in jsondata.creatives) {
                      if (f !== 'creativeListParam') {
                        eer[f] = jsondata.creatives[f]
                      }
                    }
                  })
                }
                resole()
                return
              }
              reject()
            }
          } catch (error) {
            this.$message.error('请选择已有素材广告组进行复制')
          }
        })
      })
    },
    async copyconter (row) {
      console.log('row', row)
      this.originUnitId = row.unitId
      const updatas = {
        campaignId: row.campaignId,
        batchCount: 50,
        cursor: 0,
        type: 13
      }
      this.jhConfig.campaignId = row.campaignId
      this.getUserInfoFun()
      this.getDirList(row.accountId)
      await this.getItemTers(row.unitId)
      if (this.jhConfig.creativeBuildType === 2) {
        get_jh_list.bind(this)(updatas).then(res => {
          try {
            const jsondata = JSON.parse(res)
            console.log('jsondata', jsondata)
            if (jsondata.result === 1) {
              this.copyItems = true
              this.campaignIds = jsondata.data.simpleCampaigns
            }
          } catch (error) {
            this.$message.error('获取失败', error)
          }
        })
        return
      }
      if (this.jhConfig.creativeBuildType === 0 || this.jhConfig.creativeBuildType === 1) {
        this.getPhodetelFun(row.unitId).then(_ => {
          get_jh_list.bind(this)(updatas).then(res => {
            try {
              const jsondata = JSON.parse(res)
              console.log('jsondata', jsondata)
              if (jsondata.result === 1) {
                this.copyItems = true
                this.campaignIds = jsondata.data.simpleCampaigns
              }
            } catch (error) {
              this.$message.error('获取失败', error)
            }
          })
        }).catch(err => {
          this.$message.error('请选择已有素材广告组进行复制')
        })
        return
      }
      // if (this.jhConfig.creativeBuildType === 1) {
      //   this.getPhodetelFunUnyer(row.unitId).then(_ => {
      //     get_jh_list.bind(this)(updatas).then(res => {
      //       try {
      //         const jsondata = JSON.parse(res)
      //         if (jsondata.result === 1) {
      //           this.copyItems = true
      //           this.campaignIds = jsondata.data.simpleCampaigns
      //           // this.creatives_datas = jsondata.data.creatives && jsondata.data.creatives.creativeListParam
      //         }
      //       } catch (error) {
      //         this.$message.error('获取失败', error)
      //       }
      //     })
      //   }).catch(err => {
      //     this.$message.error('请选择已有素材广告组进行复制')
      //   })
      //   return
      // }

    },
    getUserInfoFun () {
      get_user_info.bind(this)().then(res => {
        console.log('rerer', res)
        try {
          const jsondata = JSON.parse(res)
          console.log('jsondata', jsondata)
          if (jsondata.result === 1) {
            this.userinfolist = jsondata.data.userList
            this.jhConfig.liveUserId = jsondata.data.userList[0].userId
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }
      })
    },
    getPageInfos () {
      this.datas.searchParam.startTime = new Date(this.start_time[0]).getTime()
      this.datas.searchParam.endTime = new Date(this.start_time[1]).getTime()
      this.loading = true
      get_z_list.bind(this)(this.datas).then(res => {
        this.loading = false
        try {
          const jsondata = JSON.parse(res)
          console.log('jsondata', jsondata)
          if (jsondata.result === 1) {
            this.tableData = jsondata.data.data
            this.total = jsondata.data.pageInfo.totalCount
          }
        } catch (error) {
          this.$message.error('获取失败', error)
        }

      })
    },
    getPageInfossize (row) {
      console.log('getPageInfossize', row)
      this.datas.pageInfo.pageSize = row
      this.getPageInfos()
    },
    getPageInfoscurr (row) {
      console.log('getPageInfoscurr', row)
      this.datas.pageInfo.pageNum = row
      this.getPageInfos()
    },
    getcnahe () {
      this.datas.pageInfo = {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
}
</script>
